//
//  EeFilterMenu.swift
//  soapp_Example
//
//  Created by zhu xietong on 2018/5/6.
//  Copyright © 2018年 CocoaPods. All rights reserved.
//

import Foundation
import Eelay


open class EeFilterItemCell:JoCollectionCell
{
    public var button:UIButton{
        get{
            return self.item?.button ?? UIButton()
        }
    }
    
    
    var xC = NSLayoutConstraint()
    var yC = NSLayoutConstraint()
    
    public var item:FilterItemSupport? = nil
    {
        willSet{
            
            let subs = self.contentView.subviews
            for kit in subs {
                if let bt = kit as? UIButton{
                    bt.removeFromSuperview()
                }
            }
//            guard let v1 = newValue,let v2 = item else {
//                return
//            }
//            if (v1.button === v2.button){
//                return
//            }
//            item?.button.removeFromSuperview()
//            item?.owner = nil
            
//            if let aitem = item{
//                contentView.removeConstraints([xC,yC]);
//            }
        }
        didSet{
            
            
            item?.owner = self.owner
            item?.updateDisplay()

            
            if let aitem = item{
                loadItem(item: aitem)
            }
            
            guard let _ = oldValue,let _ = item else {
                return
            }

        }
    }
    
    open func loadItem(item:FilterItemSupport) {
        print("03===0ss0s00sooo",item.align.rawValue)

        switch item.align {
         case .left:
             contentView.eelay = [
                [button,[ee.L.Y]]
             ]
            break
         case .right:
            contentView.eelay = [
                [button,[ee.R.Y]]
             ]
            break
         default:
            contentView.eelay = [
                [button,[ee.X.Y]]
             ]
         }
        let bt = item.button
//
//        contentView.addSubview(bt)
//        bt.translatesAutoresizingMaskIntoConstraints = false
//
//        let x = NSLayoutConstraint(item: bt, attribute: .centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1, constant: 0)
//        let y = NSLayoutConstraint(item: bt, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0)
//        contentView.addConstraints([x,y])
        
//      r
        
        
        var aitem = item
        aitem.buttonAction = {
            bt in
            if bt.isSelected{
//                wself?.contentView.backgroundColor = .red
            }else{
//                wself?.contentView.backgroundColor = .blue
            }
        }

        
    }
    
    public weak var owner:EeFilterMenu? = nil
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.clipsToBounds = true
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}



open class EeFilterMenu:JoView,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    public var menu_width:CGFloat = UIScreen.main.bounds.width
    public var menu_height:CGFloat = 40
    
    public var control:EeFilterDropView
    
    public var cellType:EeFilterItemCell.Type = EeFilterItemCell.self
    
 
    public var collectionViewConfig:(UICollectionView)->Void = {_ in}
    
    
    public weak var controller:UIViewController?{
        didSet{
            if #available(iOS 11.0, *) {
                collectionView?.contentInsetAdjustmentBehavior = .never
            } else {
                controller?.automaticallyAdjustsScrollViewInsets = false
            }
            //设置弹出层的容器背景
            let count = controller?.navigationController?.viewControllers.count ?? 1
            if count == 1
            {
                if let tabCtr = controller?.navigationController?.tabBarController
                {
                    control.container = tabCtr.view
                    return
                }
            }
            control.container = controller?.view
        }
    }

    
    public var observerFilter:([String:Any])->Void = {_ in}
    
    public func updateFilterValues(values:[String:Any]) {
//        //计算排序
//        let orders = self.items.filter { (item) -> Bool in
//            if item.type == FilterType.order{
//                return item.button.isSelected
//            }
//            return false
//        }
//        var values = [String:[String:Any]]()
//        if let order = orders.first
//        {
//            values[order.filterKey] = order.filterValues ?? [String:Any]()
//        }
//
//        //计算过滤参数
//        let options = self.items.filter { (item) -> Bool in
//            return item.type == FilterType.options
//        }
//        for one in options{
//            if let validFilterValue = one.filterValues{
//                values[one.filterKey] = validFilterValue
//            }
//        }
        observerFilter(values)
    }
    
    public required init() {
        control = EeFilterDropView(with: nil)
        super.init(frame: .zero)
        control.menu = self
    }
    
    public required init?(coder aDecoder: NSCoder) {
        control = EeFilterDropView(with: nil)
        super.init(coder: aDecoder)
        control.menu = self
    }
    
    required public init(frame: CGRect) {
        control = EeFilterDropView(with: nil)
        super.init(frame: frame)
        control.menu = self
    }
    
    
    
    public var items = [FilterItemSupport]()
    {
        didSet{
            self.loadItems(list: items)
        }
    }
    
    public var cons = [NSLayoutConstraint]()
    public var padding:UIEdgeInsets = .zero{
        didSet{
            self.removeConstraints(cons)
            guard let v = collectionView else {
                return
            }
            let p = self.padding
            cons = self.setEeLays(lays: [
                [v,[ee.T.L.B.R,[p.top,p.left,-p.bottom,-p.right]]]
            ]).1
            setNeedsLayout()
            layoutIfNeeded()
        }
    }
    
    
    public var space:CGFloat = 1
    
    public var flow = UICollectionViewFlowLayout()

    
    public var collectionView:UICollectionView? = nil
    open override func addLayoutRules() {
        flow.scrollDirection = .horizontal
        flow.minimumInteritemSpacing = 0
        flow.minimumLineSpacing = 0
        
        flow.sectionInset = .zero
        flow.headerReferenceSize = CGSize(width: 0, height: 0)
        
        let v = UICollectionView(frame: CGRect.zero, collectionViewLayout: flow)
        v.register(cellType, forCellWithReuseIdentifier: "cell")
        v.delegate = self
        v.dataSource = self
    
        collectionViewConfig(v)
        
        let p = self.padding
        cons = self.setEeLays(lays: [
            [v,[ee.T.L.B.R,[p.top,p.left,-p.bottom,-p.right]]]
        ]).1
        
        v.backgroundColor = .clear
        self.collectionView = v
        print(v.contentInset)
        
    }
    
    open override func layoutSubviews() {
        super.layoutSubviews()
    }
    
    
    
    func itemSize(index:Int) -> CGSize {
        var flex_width:CGFloat = self.menu_width - (padding.left + padding.right) - space * items.count.cg_floatValue
        var abs_width_count = 0
        items.forEach { (item) in
            abs_width_count += 1
            flex_width = flex_width - item.itemWidth
        }
        return CGSize(width: items[index].itemWidth, height: (menu_height - self.padding.top - self.padding.bottom))
    }
    
    
    
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return itemSize(index: indexPath.item)
    }
    
    
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return .zero
    }
    
    public func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return items.count
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! EeFilterItemCell
        cell.owner = self
        cell.item = items[indexPath.item]
        return cell
    }
    
    
    
    open func loadItems(list:[FilterItemSupport]){
        
        collectionView?.reloadData()
//        collectionView?.contentInset = UIEdgeInsetsMake(-TP.topHeight, 0, 0, 0);
        
    }
    
    
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
     
    }
    
    open override var intrinsicContentSize: CGSize{
        return CGSize(width: menu_width, height: menu_height)
    }
}
